<?php

namespace app\common\service\learn;

use app\common\model\banxi\core\CoreVocabularyRange;
use app\common\model\banxi\core\CoreVocabularySetting;
use app\common\model\banxi\learn\LearnVocabularyAnswerRecord;
use app\common\model\banxi\learn\LearnVocabularyRecord;
use app\common\service\AccountService;
use app\common\service\ApiService;
use think\facade\Db;

class LearnVocabularyService extends ApiService
{

    /**
     * 开始词汇测试
     *
     * @param string|int $accountId 账户ID
     * @param string|int $accountType 账户类型
     * @param int|null $skRecordId 学习记录ID
     * @param int|null $tutorTrainerId 辅导教练ID
     * @return \think\response\Json
     */
    public function startVocabulary($accountId, $accountType, $skRecordId, $tutorTrainerId)
    {
        // 获取词汇设置和范围配置
        $CoreVocabularySettingModel = new CoreVocabularySetting();
        $settingList = $CoreVocabularySettingModel->select();
        if (empty($settingList)) {
            getResponseException('词汇量检查配置为空', [], 1, 'ERROR');
        }
        $CoreVocabularyRangeModel = new CoreVocabularyRange();
        $rangeList = $CoreVocabularyRangeModel->select();
        if (empty($rangeList)) {
            getResponseException('词汇量检查配置为空', [], 1, 'ERROR');
        }

        // 按settingId分组rangeList
        $rangeSettingGroup = [];
        foreach ($rangeList as $range) {
            $rangeSettingGroup[$range['settingId']][] = $range;
        }

        // 构建获取词汇的SQL
        $unionSqlParts = [];
        foreach ($settingList as $vocabularySetting) {
            $settingId = $vocabularySetting['id'];
            if (!isset($rangeSettingGroup[$settingId]) || empty($rangeSettingGroup[$settingId])) {
                continue;
            }

            $limit = count($rangeSettingGroup[$settingId]);
            $unionSqlParts[] = "(SELECT * FROM ba_banxi_core_vocabulary_lexicon WHERE del = 0 AND settingId = {$settingId} ORDER BY RAND() LIMIT {$limit})";
        }

        if (empty($unionSqlParts)) {
            getResponseException('词汇量检查配置为空', [], 1, 'ERROR');
        }

        $lexiconSql = implode(' UNION ALL ', $unionSqlParts);

        $vocabularyLexiconList = Db::query($lexiconSql);

        if (empty($vocabularyLexiconList)) {
            getResponseException('词汇量检查配置为空', [], 1, 'ERROR');
        }

        // 获取账户信息
        $AccountService = new AccountService();
        $accountInfo = $AccountService->getAccountInfo($accountId, $accountType);
        if (empty($accountInfo)) {
            getResponseException('账户不存在', [], 1, 'ERROR');
        }

        // 创建测试记录
        $vocabularyRecord = [
            'del' => 0,
            'skRecordId' => $skRecordId ? $skRecordId : null,
            'accountId' => $accountId,
            'accountType' => $accountType,
            'organizationId' => $accountInfo['organizationId'],
            'tutorTrainerId' => $tutorTrainerId ? $tutorTrainerId : null,
            'studentId' => ($accountType == 3) ? $accountId : null,
            'trainerId' => ($accountType == 4) ? $accountId : null,
            'isSubmit' => 0,
            'createTime' => time()
        ];

        $LearnVocabularyRecordModel = new LearnVocabularyRecord();
        $recordId = $LearnVocabularyRecordModel->insertGetId($vocabularyRecord);

        // 构造题目列表
        $answerList = [];
        foreach ($vocabularyLexiconList as $item) {
            $question = [
                'word' => $item['word'],
                'firstLetter' => $item['firstLetter'],
                'wordAudio' => $item['wordAudio'],
                'optionList' => isset($item['option']) ? json_decode($item['option'], true) : [],
                'answerList' => isset($item['answer']) ? json_decode($item['answer'], true) : [],
                'userAnswerList' => []
            ];
            $answerList[] = $question;
        }

        $result = [
            'recordId' => $recordId,
            'answerList' => $answerList
        ];

        return $result;
    }

    /**
     * 提交词汇测试结果
     *
     * @param int $studentId 学生ID
     * @param int $trainerId 教师ID
     * @param array $submit 提交数据
     * @return \think\response\Json
     */
    public function submitVocabulary($studentId, $trainerId, $submit)
    {

        $recordId = $submit['recordId'] ?? null;
        if (empty($recordId)) {
            getResponseException('测试记录不存在', [], 1, 'ERROR');
        }

        // 验证测试记录是否存在且未提交
        $LearnVocabularyRecordModel = new LearnVocabularyRecord();
        $vocabularyRecordRaw = $LearnVocabularyRecordModel->where('id', $recordId)
            ->where(function ($query) use ($studentId, $trainerId) {
                if ($studentId) {
                    $query->where('studentId', $studentId);
                }
                if ($trainerId) {
                    $query->where('trainerId', $trainerId);
                }
            })
            ->find();

        if (empty($vocabularyRecordRaw)) {
            getResponseException('测试记录不存在', [], 1, 'ERROR');
        }

        if ($vocabularyRecordRaw['isSubmit'] == 1) {
            getResponseException('测试已提交', [], 1, 'ERROR');
        }

        $questionList = $submit['answerList'] ?? [];
        if (empty($questionList)) {
            getResponseException('答题记录为空', [], 1, 'ERROR');
        }

        $answerRecordList = [];
        foreach ($questionList as $it) {
            $answerList = $it['answerList'] ?? [];
            if (empty($answerList)) {
                continue;
            }

            $userAnswerList = $it['userAnswerList'] ?? [];
            $isCorrect = (count($userAnswerList) == 1 && in_array($userAnswerList[0], $answerList)) ? 1 : 0;

            $answerRecord = [
                'recordId' => $recordId,
                'del' => 0,
                'firstLetter' => $it['firstLetter'],
                'word' => $it['word'],
                'wordAudio' => $it['wordAudio'],
                'option' => json_encode($answerList, JSON_UNESCAPED_UNICODE),
                'answer' => json_encode($it['answerList'], JSON_UNESCAPED_UNICODE),
                'userAnswer' => json_encode($userAnswerList, JSON_UNESCAPED_UNICODE),
                'isCorrect' => $isCorrect,
                'createTime' => time()
            ];

            $answerRecordList[] = $answerRecord;
        }

        // 数据计算
        $totalAnswerNum = count($answerRecordList);
        $rightNum = 0;
        foreach ($answerRecordList as $record) {
            if ($record['isCorrect'] == 1) {
                $rightNum++;
            }
        }
        $errorNum = $totalAnswerNum - $rightNum;

        // 计算等级（根据正确题数获取词汇量等级和词汇量）
        $CoreVocabularyRangeModel = new CoreVocabularyRange();
        $vocabularyRange = $CoreVocabularyRangeModel
            ->where('correctNum', '=', $rightNum)
            ->find();

        if (empty($vocabularyRange)) {
            getResponseException('未找到对应的词汇量等级', [], 1, 'ERROR');
        }

        $settingId = $vocabularyRange['settingId'];
        $vocabulary = $vocabularyRange['vocabulary'];

        // 更新测试记录
        $vocabularyRecordUpdate = [
            'rightNum' => $rightNum,
            'errorNum' => $errorNum,
            'level' => $settingId,
            'countWord' => $vocabulary,
            'isSubmit' => 1,
            'updateTime' => time()
        ];

        $LearnVocabularyRecordModel->update($vocabularyRecordUpdate, ['id' => $recordId]);

        // 批量保存答题记录
        if (!empty($answerRecordList)) {
            $LearnVocabularyAnswerRecordModel = new LearnVocabularyAnswerRecord();
            $LearnVocabularyAnswerRecordModel->insertAll($answerRecordList);
        }

        return $recordId;
    }
}
